package com.kll.carolinehmibiz.base.net.rx

import android.util.Log
import com.kll.carolinehmibiz.base.net.bean.BaseHttpResult
import com.kll.carolinehmibiz.base.net.exception.ResultCode
import io.reactivex.observers.DisposableObserver


/**
 * ====================================================
 * Created by Ziliang Cai on 2021/12/6 23:53
 * <a href="mailto:752777456@qq.com">Contact me</a>
 * ====================================================
 */
abstract class NetObserver<T> : DisposableObserver<T>() {

    private val TAG = "NetObserver"

    override fun onStart() {
        super.onStart()

//        if(!NetworkUtil.getInstance().isNetworkAvailable) {
//            L.e(TAG, "网络不可用")
//            onError(NetworkErrorException())
//            dispose()
//        } else {
//            L.d(TAG, "网络可用")
//        }
    }

    override fun onNext(t: T) {
        var a: BaseHttpResult<*> = t as BaseHttpResult<*>

        if(a.status == ResultCode.SUCCESS) {
            onSuccess(t)
        } else {
            onFail(a.status, a.message)
        }
    }

    override fun onError(e: Throwable) {
        Log.e(TAG, e.toString())

        // 自定义服务器异常，需要根据api确认后设置
        onFail(-1, "自定义服务器异常")
    }

    override fun onComplete() {
        Log.d(TAG, "网络请求流程结束")
    }

    protected abstract fun onSuccess(t: T)

    protected abstract fun onFail(code: Int, message: String)

}